package com.gzy.rpsm_admin.controller;

import com.gzy.rpsm_admin.pojo.PageResult;
import com.gzy.rpsm_admin.pojo.ResponsePojo;
import com.gzy.rpsm_admin.pojo.User.LoginUser;
import com.gzy.rpsm_admin.pojo.User.ResUser;
import com.gzy.rpsm_admin.pojo.User.User;
import com.gzy.rpsm_admin.service.UserService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Random;

@RestController
@Api(tags="用户相关接口")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/admin/login")
    @ApiOperation(value = "根据账号和密码进行登录操作，只需账号和密码。 返回个人信息和 token 字符串"
            , notes = "<span style='color:red'>模拟操作，密码为明文密码 </span>",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", dataType =
                    "String", required = true),
            @ApiImplicitParam(name = "password", dataType = "String", required =
                    true)
    })
    public ResponsePojo<ResUser> login(@ApiIgnore LoginUser
                                                user) {
        user.setUser_type((short) 1);
        ResUser result = userService.login(user);
        if (Optional.ofNullable(result).isPresent()) {
            return ResponsePojo.success(result);
        } else {
            return ResponsePojo.fail(null, "验证失败");
        }
    }
    @GetMapping("/Page/user")
    @ApiOperation(value = "返回用户分页数据")
    @ApiParam
    @ApiImplicitParams({
            @ApiImplicitParam(name="current",value ="当前页面",dataType =
                    "Integer",paramType = "query",defaultValue = "1"),
            @ApiImplicitParam(name="size",value = "页面行数",dataType =
                    "Integer",paramType = "query",defaultValue = "10"),
            @ApiImplicitParam(name="condition",value = "姓名或身份证的查 询关键字",dataType =
                    "String" ,paramType = "query"),
                    @ApiImplicitParam(name="user_type",value = "用户类型(1、管理 员；2、物业；" +
                    "3、业主；)",dataType = "Integer",required = true)
    })
    public ResponsePojo<PageResult<User>> getPage(
            @RequestParam(defaultValue = "1") Integer current,
            String condition,@RequestParam(defaultValue = "10")
            Integer size,
            @RequestParam(required = true) Integer user_type){
        PageResult<User> users = userService.pageOfUser(current,size,condition,user_type);
        ResponsePojo<PageResult<User>> res = ResponsePojo.success(users);
        return res;
    }
    @GetMapping("/admin/byid")
    @ApiOperation( value="根据 id 查找单个用户",
            notes="<span style='color:red'>根据用户 id 查询用户信息 </span>",
            response = User.class,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({ //非实体类参数
            @ApiImplicitParam(name="id",value ="用户 id",dataType =
                    "int",paramType = "query")
    })
    @ApiParam //实体类参数
    public ResponsePojo<User> queryById(@RequestParam(required =
            true) Integer id){
        User u = userService.searchById(id);
        return ResponsePojo.success(u);
    }

    @PostMapping("/updateAvatar")
    @ApiOperation( value="上传图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name="multipartFile",value ="上传的文件",dataType = "_file",
                    dataTypeClass = MultipartFile.class,required = true)
    })
    public ResponsePojo<Map<String,String>> updateAvatar(
            @RequestPart MultipartFile multipartFile,
            @RequestParam("id") Integer id, HttpServletRequest req)
    {
        //获取全局对象
        ServletContext app = req.getServletContext();
//声明返回值
        Map<String,String> map = new HashMap<String,String>();
//获取文件名，不同浏览器可能获得完整路径
        String fileName = multipartFile.getOriginalFilename();
//处理路径，获得文件名
        fileName = fileName.split("\\\\")[0];
//String path = app.getRealPath("/static/");//获得服务器文件夹的完整路径
        String path = "E:\\ideaWorkSpace\\rpsm_admin\\target\\classes\\static\\";
        //由于这里没有运行真的 tomcat，无法获得真实地址，使用打包的路径
//获得后缀名
        String sufName = fileName.substring(fileName.lastIndexOf('.')+1);
//判断后缀名
        if(!("png".equals(sufName) || "svg".equals(sufName) ||
                "gif".equals(sufName) || "jpg".equals(sufName))){
            map.put("message","不是图片文件");
            return ResponsePojo.fail(map,"后缀名不是常见图片格式");
        }
        if(multipartFile.getSize() < 500 *1024){
            map.put("message","保存成功");
            return ResponsePojo.fail(map,"");
        }
//确保唯一性，将文件保存时将重命名
        fileName = fileName.length() > 3 ?fileName.substring(0,3) : fileName ;
        fileName = fileName + System.currentTimeMillis() + new
                Random().nextInt(1000) + "." + sufName;
        try {
            multipartFile.transferTo(new File(path+"img"+File.separator,fileName));
        } catch (IOException e) {
            e.printStackTrace();
            map.put("message","IO 异常");
            return ResponsePojo.fail(map,e.getMessage());
        }
//根据路径保存到数据库
        User user = new User();
        user.setUserid(id);
        user.setUser_avatar(fileName);
        userService.updateAvatar(user);
        map.put("message","保存成功");
        return ResponsePojo.success(map);
    }
}